<?php

namespace StudyBuddy;

/**
 * Class responsible for creating
 * block with div with answers for
 * one question. Answers are found
 * in ANSWERS collection, pagination
 * is applied as necessary, sort order
 * will also be applied according to
 * param from Request
 *
 */
class Answers extends StudyBuddyObject {

    /**
     * Mongo cursor
     *
     * @var oject of type MongoCursor
     */
    protected $oCursor;

    public function __construct(Registry $oRegistry) {
        $this->oRegistry = $oRegistry;
    }

    /**
     * Get html div with answers for this one question,
     * sorted according to param passed in request
     *
     * Enclose result in <div> and add pagination to bottom
     * of div if there is any pagination necessary!
     * 
     * @todo add skip() and limit() to cursor
     * in order to use pagination. 
     *
     * @param Question $oQuestion
     *
     * @param string desired format of result. Possible
     * options are: html, array or json object
     * This will be useful for when we have an API
     *
     *
     * @return string html block
     */
    public function getAnswers(Question $oQuestion, $result = 'html') {
        $Tr = $this->oRegistry->Tr;
        $qid = $oQuestion['_id'];
        $url = $oQuestion['url'];
        d('url: ' . $url);
        d('_GET: ' . print_r($_GET, 1));

        $cond = $this->oRegistry->Request->get('sort', 's', 'i_lm_ts');
        d('cond: ' . $cond);
        $noComments = (false === (bool) $this->oRegistry->Ini->MAX_COMMENTS);
        d('no comments: ' . $noComments);
        $aFields = ($noComments || false === (bool) $this->oRegistry->Ini->SHOW_COMMENTS) ? array('comments' => 0) : array();
        /**
         * Extra security validation,
         * IMPORTANT because we should never use
         * anything in Mongo methods directly from
         * user input
         */
        if (!in_array($cond, array('i_ts', 'i_votes', 'i_lm_ts'))) {
            throw new Exception('invalid value of param "cond" was: ' . $cond);
        }

        $where = array('i_qid' => $qid);
        if (!$this->oRegistry->Viewer->isModerator()) {
            d('not moderator');
            $where['i_del_ts'] = null;
        }

        switch ($cond) {
            case 'i_ts':
                $sort = array('i_ts' => 1);
                break;

            case 'i_votes':
                $sort = array('i_votes' => -1);
                break;

            default:
                $sort = array($cond => -1);
        }

        $cursor = $this->oRegistry->Mongo->ANSWERS->find($where, $aFields);
        d('$cursor: ' . gettype($cursor));
        $cursor->sort($sort);
        $oPager = Paginator::factory($this->oRegistry);
        $oPager->paginate($cursor, $this->oRegistry->Ini->PER_PAGE_ANSWERS, array('path' => $this->oRegistry->Ini->SITE_URL . '/q' . $qid . '/' . $url . '/' . $cond,
            'append' => false)); //, 'fileName' => '&pageID=%d'

        $pagerLinks = $oPager->getLinks();

        $func = null;
        $ownerId = $oQuestion['i_uid'];
        $showLink = (($ownerId > 0) && ($this->oRegistry->Viewer->isModerator() || $ownerId == $this->oRegistry->Viewer->getUid()) );

        d('adding accept link callback function');
        /**
         * @todo Translate strings
         */
        $accept = $Tr['Accept'];
        $alt = $Tr['Click to accept this as best answer'];
        $alt2 = $Tr['Owner of the question accepted this as best answer'];
        $noComments = ($noComments) ? ' nocomments' : '';
        $addcomment = $Tr['add comment'];
        $edited = $Tr['Edited'];
        $reply = $Tr['Reply'];
        $reply_t = $Tr['Reply to this comment'];

        $func = function(&$a) use ($accept, $alt, $alt2, $addcomment, $reply, $reply_t, $edited, $showLink, $noComments) {
                    /**
                     * Don't show Accept link for
                     * already accepted answer
                     */
                    if (!($a['accepted'])) {
                        if ($showLink) {
                            $a['accept_link'] = '<a class="accept ttt" title="' . $alt . '" href="/accept/' . $a['_id'] . '"></a>';
                        }
                    } else {
                        $a['accepted'] = '<img src="/images/accepted.png" alt="Best answer" class="ttt" title="' . $alt2 . '">';
                    }

                    $a['add_comment'] = $addcomment;
                    $a['nocomments'] = $noComments;
                    $a['reply'] = $reply;
                    $a['reply_t'] = $reply_t;
                    $a['edited'] = $edited;
                };

        /**
         * Create div with answers, append pagination links
         * to bottom and return the whole div block
         */
        $answers = \tplAnswer::loop($cursor, true, $func) . $pagerLinks;

        return '
            <div class="ctl-ct">
                <div class="ctl-boxq">' . 
                    $answers .
                '</div>
            </div>';
    }

}
